<template>
    <div class="ve_container">
        <!-- 搜索 -->
        <el-form ref="queryForm" :inline="true" :model="params">
            <el-form-item label="创建时间" prop="createTime">
                <el-input
                    v-model="createTime"
                    placeholder="请输入创建时间"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="关联ID" prop="id">
                <el-input
                    v-model="id"
                    placeholder="请输入关联ID"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="是否删除" prop="isDeleted">
                <el-input
                    v-model="isDeleted"
                    placeholder="请输入是否删除"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="更新时间" prop="updateTime">
                <el-input
                    v-model="updateTime"
                    placeholder="请输入更新时间"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="用户ID" prop="userId">
                <el-input
                    v-model="userId"
                    placeholder="请输入用户ID"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="区域编码" prop="zoneCode">
                <el-input
                    v-model="zoneCode"
                    placeholder="请输入区域编码"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item label="区域ID" prop="zoneId">
                <el-input
                    v-model="zoneId"
                    placeholder="请输入区域ID"
                    clearable
                ></el-input>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    @click="onSubmit(params, getDataList)"
                >
                    {{ buttons.search.name }}
                </el-button>
                <el-button @click="resetForm(queryForm, params, getDataList)">
                    重置
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <ve-table
            :table="{
                data: tableData,
            }"
            :pagination="{
                onSizeChange: (val) =>
                    handleSizeChange(val, params, getDataList),
                onCurrentChange: (val) =>
                    handleCurrentChange(val, params, getDataList),
                currentPage: current,
                pageSize: size,
                total: total,
            }"
        >
            <template #tool_bar>
                <el-button
                    v-if="!isShowDialog"
                    v-permission="['add']"
                    size="small"
                    type="primary"
                    @click="handleEdit(buttons.add.name)"
                >
                    {{ buttons.add.name }}
                </el-button>

                <el-button
                    v-permission="['downLoadExcel']"
                    size="small"
                    type="primary"
                    @click="downLoadExcel()"
                >
                    {{ buttons.downLoadExcel.name }}
                </el-button>
                <el-button
                    v-permission="['downLoadExportTemplateExcel']"
                    size="small"
                    type="primary"
                    @click="downLoadExportTemplateExcel()"
                >
                    {{ buttons.downLoadExportTemplateExcel.name }}
                </el-button>
                <el-button
                    v-if="isShowDialog"
                    v-permission="['importExcel']"
                    size="small"
                    type="primary"
                    @click="handleUpload(buttons.importExcel.name)"
                >
                    {{ buttons.importExcel.name }}
                </el-button>
            </template>

            <el-table-column
                prop="createTime"
                label="创建时间 "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="id"
                label="关联ID "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="isDeleted"
                label="是否删除 "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="updateTime"
                label="更新时间 "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="userId"
                label="用户ID "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="zoneCode"
                label="区域编码 "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <el-table-column
                prop="zoneId"
                label="区域ID "
                :show-overflow-tooltip="showOverflowTooltip"
            ></el-table-column>

            <!--            <el-table-column prop="username" label="用户名"> </el-table-column>-->
            <el-table-column fixed="right" label="操作" v-if="!isShowDialog">
                <template v-slot:default="{ row }">
                    <el-button
                        v-permission="['edit']"
                        @click.prevent="handleEdit(buttons.edit.name, row)"
                        type="primary"
                        size="small"
                    >
                        {{ buttons.edit.name }}
                    </el-button>
                    <el-button
                        v-permission="['del']"
                        @click.prevent="handleDel(row.id)"
                        type="danger"
                        size="small"
                    >
                        {{ buttons.del.name }}
                    </el-button>
                </template>
            </el-table-column>
        </ve-table>

        <!-- 编辑组件 -->
        <SysZoneUserEdit
            v-if="showDialog"
            :rowData="rowData"
            :title="dialogTitle"
            :showDialog="showDialog"
            @closeDialog="closeEditDialog($event)"
        />
        <!-- 上传组件 -->
        <SysZoneUserUpload
            v-if="showUploadDialog"
            :title="dialogTitle"
            :showDialog="showUploadDialog"
            @closeDialog="closeUploadDialog($event)"
        />
    </div>
</template>
<script>
import menu from "./components/menu";
import { moduleName } from "@/config";

export default {
    data: () => ({
        description: "用户区域关联关系管理",
        buttons: {
            search: { name: "查询" },
            add: { name: "添加" },
            edit: { name: "编辑" },
            del: { name: "删除" },
            downLoadExcel: { name: "导出结果" },
            downLoadExportTemplateExcel: { name: "导出模版" },
            importExcel: { name: "导入" },
        },
        // type 0:目录 1：菜单 2：按钮
        type: "1",
        icon: "Stamp",
        name: "用户区域关联关系管理",
        parentMenu: menu,
        module: moduleName,
    }),
};
</script>

<script setup>
import SysZoneUserEdit from "./components/SysZoneUserEdit.vue";
import SysZoneUserUpload from "./components/SysZoneUserUpload.vue";
import {
    reactive,
    toRefs,
    ref,
    onMounted,
    getCurrentInstance,
    defineProps,
} from "vue";
import { ElMessage } from "element-plus";

//*导入公共查询方法
import {
    onSubmit,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
} from "@/views/pages/common";

const props = defineProps({
    queryParams: {
        type: Object,
        default: null,
    },
    isShowDialog: {
        type: Boolean,
        default: false,
    },
    showOverflowTooltip: {
        type: Boolean,
        default: true,
    },
});

const { queryParams, isShowDialog, showOverflowTooltip } = toRefs(props);

const { proxy } = getCurrentInstance();

const rowData = ref(null);
const dialogTitle = ref("");
const showDialog = ref(false);
const showUploadDialog = ref(false);

const queryForm = ref(null);
const tableData = ref([]);
const params = reactive({
    createTime: "",
    id: "",
    isDeleted: "",
    updateTime: "",
    userId: "",
    zoneCode: "",
    zoneId: "",
    size: 10,
    current: 1,
    total: 0,
});
const {
    createTime,
    id,
    isDeleted,
    updateTime,
    userId,
    zoneCode,
    zoneId,
    size,
    current,
    total,
} = toRefs(params);

queryParams.value &&
    ((params.createTime = queryParams.value.createTime),
    (params.id = queryParams.value.id),
    (params.isDeleted = queryParams.value.isDeleted),
    (params.updateTime = queryParams.value.updateTime),
    (params.userId = queryParams.value.userId),
    (params.zoneCode = queryParams.value.zoneCode),
    (params.zoneId = queryParams.value.zoneId));
/**
 * @description:添加or编辑事件
 * @return {*}
 * @param title
 * @param row
 */
const handleEdit = (title, row = null) => {
    showDialog.value = true;
    dialogTitle.value = title;
    rowData.value = row;
};
/**
 * @description: dialog事件
 * @return {*}
 * @param e
 */
const closeEditDialog = (e) => {
    showDialog.value = e;
    getDataList();
};

/**
 * @description: 上传Excel文件
 * @return {*}
 * @param title
 * @param row
 */
const handleUpload = (title, row = null) => {
    showUploadDialog.value = true;
    dialogTitle.value = title;
    rowData.value = row;
};
/**
 * @description: dialog事件
 * @return {*}
 * @param e
 */
const closeUploadDialog = (e) => {
    showUploadDialog.value = e;
    getDataList();
};
/**删除行数据
 * @description:
 * @param {*}
 * @return {*}
 */
const handleDel = (id) => {
    proxy
        .$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
        })
        .then(async () => {
            try {
                const { code } = await VE_API.SysZoneUserApi.sysZoneUserRemove({
                    id,
                });
                if (code === 0) {
                    ElMessage.success("删除成功");
                    getDataList();
                } else {
                    // 业务错误已在axios拦截器中处理
                    console.warn("删除用户失败:", code);
                }
            } catch (error) {
                // 网络错误等异常情况已经在axios拦截器中处理
                console.error("删除用户异常:", error);
            }
        })
        .catch(() => {
            proxy.$message({
                type: "info",
                message: "已取消删除",
            });
        });
};

/**
 * 文件模版下载
 */
const downLoadExportTemplateExcel = async () => {
    queryForm.value.validate(async (valid) => {
        if (valid) {
            try {
                let res =
                    await VE_API.SysZoneUserApi.sysZoneUserExportTemplateExcel(
                        params,
                        {
                            responseType: "blob",
                        },
                    );

                let fileName = res.headers["file-name"];
                // 获取文件名
                fileName = decodeURIComponent(fileName);
                let url = window.URL.createObjectURL(new Blob([res.data]));
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                // eslint-disable-next-line no-undef
                link.setAttribute("download", fileName); //指定下载后的文件名，防跳转
                document.body.appendChild(link);
                link.click();
                // 释放内存
                window.URL.revokeObjectURL(link.href);
            } catch (error) {
                // 网络错误等异常情况已经在axios拦截器中处理
                console.error("下载模板文件异常:", error);
            }
        } else {
            return false;
        }
    });
};

/**
 * 文件下载
 */
const downLoadExcel = async () => {
    queryForm.value.validate(async (valid) => {
        if (valid) {
            try {
                let res = await VE_API.SysZoneUserApi.sysZoneUserExportExcel(
                    params,
                    {
                        responseType: "blob",
                    },
                );
                let fileName = res.headers["file-name"];
                // 获取文件名
                fileName = decodeURIComponent(fileName);
                let url = window.URL.createObjectURL(new Blob([res.data]));
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                // eslint-disable-next-line no-undef
                link.setAttribute("download", fileName); //指定下载后的文件名，防跳转
                document.body.appendChild(link);
                link.click();
                // 释放内存
                window.URL.revokeObjectURL(link.href);
            } catch (error) {
                // 网络错误等异常情况已经在axios拦截器中处理
                console.error("下载文件异常:", error);
            }
        } else {
            return false;
        }
    });
};
/**
 * @description: 获取列表数据
 * @param {*}
 * @return {*}
 */
const getDataList = async () => {
    try {
        const { code, data } =
            await VE_API.SysZoneUserApi.sysZoneUserFindPage(params);
        if (code === 0) {
            const { size, current, total, records } = data;
            params.size = size;
            params.current = current;
            params.total = total;
            tableData.value = records;
        } else {
            // 业务错误已在axios拦截器中处理
            console.warn("获取用户列表失败:", data?.message);
        }
    } catch (error) {
        // 网络错误等异常情况已经在axios拦截器中处理
        console.error("获取用户列表异常:", error);
    }
};
onMounted(async () => {
    await getDataList();
});
</script>

<style lang="scss" scoped></style>
